package com.ruoyi.system.service.msg.enricher;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.entity.ConstructionStageDO;
import com.ruoyi.system.entity.MsgPushTaskDO;
import com.ruoyi.system.entity.ConstructionProjectItemDO;
import com.ruoyi.system.enums.MsgTypeEnum;
import com.ruoyi.system.mapper.ConstructionStageMapper;
import com.ruoyi.system.mapper.ConstructionItemMapper;
import com.ruoyi.system.service.AcceptanceChecklistInstanceService;
import com.ruoyi.system.service.msg.MsgDetailEnricher;
import com.ruoyi.system.vo.AcceptanceChecklistInstanceVO;
import com.ruoyi.system.vo.H5MsgDetailVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 阶段验收消息详情丰富器
 * 用于丰富阶段验收类型消息的详情信息，包括阶段信息、验收事项、验收模板等
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Component
public class AcceptStageMsgEnricher implements MsgDetailEnricher {

    @Resource
    private AcceptanceChecklistInstanceService instanceService;

    @Resource
    private ConstructionStageMapper constructionStageMapper;

    @Resource
    private ConstructionItemMapper constructionItemMapper;

    @Override
    public boolean supports(Integer msgType) {
        return Objects.equals(msgType, MsgTypeEnum.ACCEPTANCE_CHECKLIST.getCode());
    }

    @Override
    public void enrich(H5MsgDetailVO vo, MsgPushTaskDO task) {
        if (task.getBusinessId() == null || task.getBusinessId().trim().isEmpty()) {
            return;
        }

        try {
            // 1. 根据消息子项ID获取验收单实例
            if (vo.getItemId() != null) {
                AcceptanceChecklistInstanceVO checklist = instanceService.getInstanceByMsgItemId(vo.getItemId());
                vo.setAcceptanceChecklist(checklist);
            }

            // 2. 获取阶段信息
            Long stageId = Long.valueOf(task.getBusinessId());
            ConstructionStageDO stage = constructionStageMapper.selectById(stageId);
            if (stage != null) {
                // 3. 获取该阶段下的所有验收事项
                List<ConstructionProjectItemDO> stageItems = constructionItemMapper.selectList(
                        new LambdaQueryWrapper<ConstructionProjectItemDO>()
                                .eq(ConstructionProjectItemDO::getStageId, stageId)
                                .eq(ConstructionProjectItemDO::getIsDeleted, 0)
                                .orderByAsc(ConstructionProjectItemDO::getId)
                );
                stage.setProjectItems(stageItems);
            }
        } catch (Exception e) {
            // 记录日志但不影响主流程
            System.err.println("获取阶段验收信息时发生异常: " + e.getMessage());
        }
    }
}

